<?php


namespace app\common\business;

use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\QuestionDetail;
use app\common\utils\Questions;
use app\common\utils\Str;
use catcher\CatchResponse;
use catcher\exceptions\CatchException;
use catcher\exceptions\FailedException;
use MongoDB\Model\BSONArray;
use think\db\exception\PDOException;
use think\Exception;
use think\facade\Db;

class Project
{

    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\Project();
    }

    /**
     * @param array $data
     * @return \app\common\model\Project|array|mixed|\think\Model|null
     */
    public function createProject(array $data)
    {

        $connection = ZhyxMongo::getInstance()->connection;
        $session = $connection->startSession();
        try {
            /* if (isset($data["survey"]) && is_string($data["survey"])) {
                 $data["survey"] = Questions::getQuestionChartType($data["survey"]);
              }*/
            //执行数据的写入操作
            //开启事务

            $session->startTransaction(['session' => $session]);
            $appendData["parentId"] = $data["parentId"] ?? "0";
            if ($data["mode"] === "folder") {
                $appendData["status"] = 1;
                $appendData["total"] = 0;
                $appendData["sort_no"] = 0;
            } else {
                $data["status"] = $data["status"] ?? 0;
                $appendData["answer_number"] = 0;
                $appendData["sort_no"] = 9999;
                if (is_string($data["dept_list"])) {
                    $data["dept_list"] = json_decode($data["dept_list"], true, 512, JSON_THROW_ON_ERROR);
                }
                if (is_string($data["disease"])) {
                    $data["disease"] = json_decode($data["disease"], true, 512, JSON_THROW_ON_ERROR);
                }
                if (is_string($data["survey"])) {
                    $data["survey"] = json_decode($data["survey"], true, 512, JSON_THROW_ON_ERROR);
                }
            }
            $appendData["projectId"] = Str::alphaID(6);
            $appendData["created_at"] = time();
            $appendData["updated_at"] = time();
            $appendData["deleted_at"] = 0;
            $data = array_merge($appendData, $data);

            $result = ZhyxMongo::getInstance()->setCollection("project")->insertOne($data, ['session' => $session]);
            if ($result) {
                //执行问卷问题表入库写入
                if (isset($data["survey"]) && !empty($data["survey"])) {
                    (new QuestionDetail())->saveQuestions($data["survey"], $result->getInsertedId(), $session);
                }
                if ($appendData["parentId"] !== "0") {
                    $this->model->incNumber($data["parentId"], "total", $session);
                }
                $session->commitTransaction();
                return $this->model->find($result->getInsertedId());
            }
        } catch (\Exception $exception) {
            if ($session->getTransactionState() !== "none") {
                $session->abortTransaction();
            }
            throw new FailedException($exception->getMessage());
        }
        return null;
    }


    public function modifyProject(string $projectId, array $modifyData): bool
    {
        $connection = ZhyxMongo::getInstance()->connection;

        $session = $connection->startSession();
        try {
            $projectInfo = $this->model->getProjectInfo($projectId);
            if (empty($projectInfo)) {
                throw new FailedException("信息不存在");
            }
            $surveyData = $modifyData["survey"] ?? [];
            if ($projectInfo["status"] === 1 && $projectInfo["mode"] === "survey" && !empty($surveyData) && !empty($modifyData["survey"])) {
                throw new FailedException("问卷已经开始，不能修改");
            }
            $session->startTransaction(['session' => $session]);
            //执行修改试卷
            if (isset($modifyData["parentId"]) && $projectInfo["parentId"] !== $modifyData["parentId"] && $projectInfo["mode"] === "survey") {
                if ($modifyData["parentId"] !== "0") {
                    $this->model->incNumber($modifyData["parentId"], "total", $session);
                } else {
                    $this->model->decNumber($projectInfo["parentId"], "total", $session);
                }
            }
            $modifyData["updated_at"] = time();
            if (isset($modifyData["dept_list"])) {
                $modifyData["dept_list"] = new BSONArray($modifyData["dept_list"]);
            }
            if (isset($modifyData["disease"])) {
                $modifyData["disease"] = new BSONArray($modifyData["disease"]);
            }
            $result = ZhyxMongo::getInstance()->setCollection('project')->updateOne(["projectId" => $projectId], ['$set' => $modifyData], ['session' => $session]);

            if (!empty($surveyData)) {
                (new QuestionDetail())->saveQuestions($surveyData, $projectInfo["id"], $session);
            }
            $session->commitTransaction();
            return true;
        } catch (\Exception $exception) {
            if ($session->getTransactionState() !== "none") {
                $session->abortTransaction();
            }
            throw new FailedException($exception->getMessage());
        }
    }

    public function getList(bool $isShowAllData = false): \think\Paginator
    {

        //获取用户下级ID
        $userIds = $this->model->getUserIds();
        //判断用户所在角色的数据权限
        $depIds = $this->model->getDeptListByUser(0);

        return $this->model->getLists($userIds, $depIds, $isShowAllData);


    }

    public function getProjectTree()
    {
        //获取用户下级ID
        $userIds = $this->model->getUserIds();
        //判断用户所在角色的数据权限
        $depIds = $this->model->getDeptListByUser(0);
        return $this->model->getListToTree($userIds, $depIds);
    }

    public function getProjectInfo(string $projectId, $field = '*')
    {
        return $this->model->where("projectId", "=", $projectId)->find();

    }


    public function DelProject(string $projectId): bool
    {
        $projectInfo = $this->getProjectInfo($projectId);
        if (empty($projectInfo)) {
            throw new FailedException("暂无问卷/文件夹");
        }
        if ($projectInfo["status"] === 1 && $projectInfo["mode"] === "survey") {
            throw new FailedException("当前问卷已发布，不能进行删除操作");
        }
        //判断如果是文件夹并且下级有文件
        if ($projectInfo["mode"] === "folder") {
            $fileCount = $this->model->where("parentId", "=", $projectId)->count();
            if ($fileCount > 0) {
                throw new FailedException("文件夹下有问卷，不能进行移除操作");
            }
        }
        $result = $projectInfo->delete();
        if ($result !== false && $projectInfo["parentId"] !== "0") {
            //判断如果当前文件是在文件夹内则需要将文件夹数量进行-1操作
            $this->model->decNumber($projectInfo["parentId"], "total");
        }
        return $result;
    }

    public function getProjectByCondition(array $condition)
    {
        $condition[] = ["mode", "=", "survey"];
        $condition[] = ["status", "=", 1];
        return $this->model->where($condition)->field(["id", "name", "projectId"])->select();
    }


}